

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/images/common/favicon.png">
  <link rel="icon" href="/images/common/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Robbin">
  <meta name="keywords" content="">
  
    <meta name="description" content="前言Vue项目开发完毕后，对项目进行打包发布之前，必不可少的操作就是项目优化，这也是程序猿的加分项。跟随本文的脚步来看看如何对项目进行优化吧~">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue项目优化打包——前端加分项">
<meta property="og:url" content="http://example.com/2022/03/08/article-7/index.html">
<meta property="og:site_name" content="前端阿开">
<meta property="og:description" content="前言Vue项目开发完毕后，对项目进行打包发布之前，必不可少的操作就是项目优化，这也是程序猿的加分项。跟随本文的脚步来看看如何对项目进行优化吧~">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/images/common/vue.jpeg">
<meta property="article:published_time" content="2022-03-08T05:38:47.000Z">
<meta property="article:modified_time" content="2022-03-08T05:38:47.000Z">
<meta property="article:author" content="web_akai">
<meta property="article:tag" content="#Vue.js">
<meta property="article:tag" content="#前端">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="http://example.com/images/common/vue.jpeg">
  
  
  <title>Vue项目优化打包——前端加分项 - 前端阿开</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"baidu":"b2ef8b4e438bfbfa9667837d1124fb6c","google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"A6A3KekcB19LfYQfObiJlDAu-gzGzoHsz","app_key":"h5J0Jt6wCaR3HtH5I0brXmRk","server_url":null,"path":"window.location.pathname","ignore_local":true}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.0.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>前端阿开</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/message/">
                <i class="iconfont icon-medium-fill"></i>
                留言板
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" target="_self" href="javascript:;" role="button"
                 data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="iconfont icon-books"></i>
                文档
              </a>
              <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/">
                    
                    主题博客
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/docs/guide/">
                    
                    配置指南
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/docs/icon/">
                    
                    图标用法
                  </a>
                
              </div>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/images/common/default_index_img.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="Vue项目优化打包——前端加分项">
              
            </span>

            
              <div class="mt-3">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-author" aria-hidden="true"></i>
      Robbin
    </span>
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-03-08 13:38" pubdate>
        2022-03-08, 13:38
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      3.9k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      33 分钟
    </span>
  

  
  
    
      <!-- LeanCloud 统计文章PV -->
      <span id="leancloud-page-views-container" class="post-meta" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="leancloud-page-views"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Vue项目优化打包——前端加分项</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：2 年前
                
              </p>
            
            <div class="markdown-body">
              <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p class="note note-success">Vue项目开发完毕后，对项目进行打包发布之前，必不可少的操作就是项目优化，这也是程序猿的加分项。跟随本文的脚步来看看如何对项目进行优化吧~</p>

<span id="more"></span>

<h2 id="一、路由懒加载"><a href="#一、路由懒加载" class="headerlink" title="一、路由懒加载"></a>一、路由懒加载</h2><h3 id="1-为什么需要路由懒加载"><a href="#1-为什么需要路由懒加载" class="headerlink" title="1. 为什么需要路由懒加载"></a>1. 为什么需要路由懒加载</h3><p>当刚运行项目的时候，发现刚进入页面，就将所有的 js 文件和 css 文件加载了进来，这一进程十分的消耗时间。<br>如果打开哪个页面就对应的加载响应页面的 js 文件和 css 文件，那么页面加载速度会大大提升。</p>
<h3 id="2-如何实现路由懒加载"><a href="#2-如何实现路由懒加载" class="headerlink" title="2. 如何实现路由懒加载"></a>2. 如何实现路由懒加载</h3><p>vue 官方文档：<a target="_blank" rel="noopener" href="https://router.vuejs.org/zh/guide/advanced/lazy-loading.html">路由懒加载</a>代码如下（示例）:</p>
<figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs JavaScript">&#123;<br>  <span class="hljs-attr">path</span>: <span class="hljs-string">&#x27;/login&#x27;</span>,<br>  <span class="hljs-attr">component</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-title function_">import</span>(<span class="hljs-string">&#x27;@/views/login/index&#x27;</span>),<br>  <span class="hljs-attr">hidden</span>: <span class="hljs-literal">true</span><br>&#125;,<br></code></pre></div></td></tr></table></figure>

<h3 id="3-路由懒加载中的魔法注释"><a href="#3-路由懒加载中的魔法注释" class="headerlink" title="3. 路由懒加载中的魔法注释"></a>3. 路由懒加载中的魔法注释</h3><p>通过在注释中指定 <code>webpackChunkName</code>，可以自定义这个文件的名字。<br>代码如下（示例）:</p>
<figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs JavaScript">components = <span class="hljs-function">() =&gt;</span> <span class="hljs-title function_">import</span>(<span class="hljs-regexp">/_ webpackChunkName:&quot;login&quot;_/</span> <span class="hljs-string">&quot;../component/Login.vue&quot;</span>)<br></code></pre></div></td></tr></table></figure>

<h2 id="二、分析包大小"><a href="#二、分析包大小" class="headerlink" title="二、分析包大小"></a>二、分析包大小</h2><h3 id="1-需求"><a href="#1-需求" class="headerlink" title="1. 需求"></a>1. 需求</h3><p>想要知道打包生成的文件中，每个文件所占的空间大小。以便于我们分析，对代码进行优化处理。</p>
<h3 id="2-如何生成打包分析文件"><a href="#2-如何生成打包分析文件" class="headerlink" title="2. 如何生成打包分析文件"></a>2. 如何生成打包分析文件</h3><p>终端中运行 <code>npm run preview -- --report</code>, 这个命令会从我们的入口 main.js 进行依赖分析，分析出各个包的大小。最终会在生成的 dist 文件夹下生成一个 report.html 的文件，打开后就可以看到我们在项目使用文件占据的空间大小啦~<br>(效果图如下：)</p>
<p><img src="/./images/a8edced7345a44a1b732df1bb2596db1.jpg" srcset="/img/loading.gif" lazyload alt="report.html"></p>
<h2 id="三、webpack-配置排除打包"><a href="#三、webpack-配置排除打包" class="headerlink" title="三、webpack 配置排除打包"></a>三、webpack 配置排除打包</h2><h3 id="1-需求-1"><a href="#1-需求-1" class="headerlink" title="1. 需求"></a>1. 需求</h3><p>将一些不常用的包，排除在生成的打包文件以外。例如：上图所示的 xsxl.js 、 element.js，可以将其排除在打包生成的文件以外</p>
<h3 id="2-排除打包"><a href="#2-排除打包" class="headerlink" title="2. 排除打包"></a>2. 排除打包</h3><p>找到 <code>vue.config.js</code>， 添加 <code>externals</code> 项，具体如下：<br>代码如下（示例）：</p>
<figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs JavaScript"><span class="hljs-attr">configureWebpack</span>: &#123;<br>  <span class="hljs-comment">// 配置单页应用程序的页面的标题</span><br>  <span class="hljs-attr">name</span>: name,<br>  <span class="hljs-attr">externals</span>: &#123;<br>    /\*\*<br>    _ externals 对象属性解析。<br>    _ 基本格式：<br>    _ <span class="hljs-string">&#x27;包名&#x27;</span> : <span class="hljs-string">&#x27;在项目中引入的名字&#x27;</span><br>    _<br>    \*/<br>    <span class="hljs-string">&#x27;vue&#x27;</span>: <span class="hljs-string">&#x27;Vue&#x27;</span>,<br>    <span class="hljs-string">&#x27;element-ui&#x27;</span>: <span class="hljs-string">&#x27;ElementUI&#x27;</span>,<br>    <span class="hljs-string">&#x27;xlsx&#x27;</span>: <span class="hljs-string">&#x27;XLSX&#x27;</span><br>    &#125;,<br>    <span class="hljs-attr">resolve</span>: &#123;<br>    <span class="hljs-attr">alias</span>: &#123;<br>    <span class="hljs-string">&#x27;@&#x27;</span>: <span class="hljs-title function_">resolve</span>(<span class="hljs-string">&#x27;src&#x27;</span>)<br>    &#125;<br>  &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<h2 id="四、-引用网络资源"><a href="#四、-引用网络资源" class="headerlink" title="四、 引用网络资源"></a>四、 引用网络资源</h2><h3 id="1-需求-2"><a href="#1-需求-2" class="headerlink" title="1. 需求"></a>1. 需求</h3><p>我们进行了上一步操作以后，打包生成后的包小了很多。但是呢，没有这些依赖包的话，项目上线是没有办法运行的。那么就需要引用网络中的资源，来支持我们代码的运行。</p>
<h3 id="2-CDN"><a href="#2-CDN" class="headerlink" title="2. CDN"></a>2. CDN</h3><p><code>CDN</code> 全称叫做“Content Delivery Network”，中文叫内容分发网络。我们用它来提高访问速度<br>把一些静态资源：css， .js，图片，视频放在第三方的 CDN 服务器上，可以加速访问速度。</p>
<h4 id="好处："><a href="#好处：" class="headerlink" title="好处："></a>好处：</h4><p>减少应用打包出来的包体积<br>加快静态资源的访问<br>利用浏览器缓存，不会变动的文件长期缓存</p>
<h3 id="3-实现步骤"><a href="#3-实现步骤" class="headerlink" title="3. 实现步骤"></a>3. 实现步骤</h3><p>注意:在开发环境时，文件资源还是可以从本地 <code>node_modules</code> 中取出，而只有项目上线了，才需要去使用外部资源。此时我们可以使用环境变量来进行区分。具体如下：<br>代码如下（示例）：<br>在 <code>vue.config.js</code> 文件中:</p>
<figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs JavaScript"><span class="hljs-keyword">let</span> externals = &#123;&#125;<br><span class="hljs-keyword">let</span> cdn = &#123; <span class="hljs-attr">css</span>: [], <span class="hljs-attr">js</span>: [] &#125;<br><span class="hljs-keyword">const</span> isProduction = process.<span class="hljs-property">env</span>.<span class="hljs-property">NODE_ENV</span> === <span class="hljs-string">&#x27;production&#x27;</span> <span class="hljs-comment">// 判断是否是生产环境</span><br><span class="hljs-keyword">if</span> (isProduction) &#123;<br>  externals = &#123;<br>      <span class="hljs-comment">/**</span><br><span class="hljs-comment">      * externals 对象属性解析：</span><br><span class="hljs-comment">      * &#x27;包名&#x27; : &#x27;在项目中引入的名字&#x27;</span><br><span class="hljs-comment">    */</span><br>      <span class="hljs-string">&#x27;vue&#x27;</span>: <span class="hljs-string">&#x27;Vue&#x27;</span>,<br>      <span class="hljs-string">&#x27;element-ui&#x27;</span>: <span class="hljs-string">&#x27;ELEMENT&#x27;</span>,<br>      <span class="hljs-string">&#x27;xlsx&#x27;</span>: <span class="hljs-string">&#x27;XLSX&#x27;</span><br>  &#125;<br>  cdn = &#123;<br>    <span class="hljs-attr">css</span>: [<br>      <span class="hljs-string">&#x27;https://unpkg.com/element-ui/lib/theme-chalk/index.css&#x27;</span> <span class="hljs-comment">// element-ui css 样式表</span><br>    ],<br>    <span class="hljs-attr">js</span>: [<br>      <span class="hljs-comment">// vue must at first!</span><br>      <span class="hljs-string">&#x27;https://unpkg.com/vue@2.6.12/dist/vue.js&#x27;</span>, <span class="hljs-comment">// vuejs</span><br>      <span class="hljs-string">&#x27;https://unpkg.com/element-ui/lib/index.js&#x27;</span>, <span class="hljs-comment">// element-ui js</span><br>      <span class="hljs-string">&#x27;https://cdn.jsdelivr.net/npm/xlsx@0.16.6/dist/xlsx.full.min.js&#x27;</span>, <span class="hljs-comment">// xlsx</span><br>    ]<br>  &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<p>webpack 配置 <code>externals</code> 配置项</p>
<figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs JavaScript"><span class="hljs-attr">configureWebpack</span>: &#123;<br>  <span class="hljs-comment">// 配置单页应用程序的页面的标题</span><br>  <span class="hljs-attr">name</span>: name,<br>  <span class="hljs-attr">externals</span>: externals,<br>  <span class="hljs-attr">resolve</span>: &#123;<br>    <span class="hljs-attr">alias</span>: &#123;<br>      <span class="hljs-string">&#x27;@&#x27;</span>: <span class="hljs-title function_">resolve</span>(<span class="hljs-string">&#x27;src&#x27;</span>)<br>    &#125;<br>  &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<p>通过 <code>html-webpack-plugin</code> 注入到 <code>index.html</code> 之中:<br>在<code>vue.config.js</code>文件中配置:</p>
<figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs JavaScript"><span class="hljs-title function_">chainWebpack</span>(<span class="hljs-params">config</span>) &#123;<br>  config.<span class="hljs-title function_">plugin</span>(<span class="hljs-string">&#x27;preload&#x27;</span>).<span class="hljs-title function_">tap</span>(<span class="hljs-function">() =&gt;</span> [<br>    &#123;<br>      <span class="hljs-attr">rel</span>: <span class="hljs-string">&#x27;preload&#x27;</span>,<br>      <span class="hljs-attr">fileBlacklist</span>: [<span class="hljs-regexp">/\.map$/</span>, <span class="hljs-regexp">/hot-update\.js$/</span>, <span class="hljs-regexp">/runtime\..*\.js$/</span>],<br>      <span class="hljs-attr">include</span>: <span class="hljs-string">&#x27;initial&#x27;</span><br>    &#125;<br>  ])<br>  <span class="hljs-comment">// 注入cdn变量 (打包时会执行)</span><br>  config.<span class="hljs-title function_">plugin</span>(<span class="hljs-string">&#x27;html&#x27;</span>).<span class="hljs-title function_">tap</span>(<span class="hljs-function"><span class="hljs-params">args</span> =&gt;</span> &#123;<br>    args[<span class="hljs-number">0</span>].<span class="hljs-property">cdn</span> = cdn <span class="hljs-comment">// 配置cdn给插件</span><br>    <span class="hljs-keyword">return</span> args<br>  &#125;)<br>  <span class="hljs-comment">// 省略其他...</span><br>&#125;<br></code></pre></div></td></tr></table></figure>

<p>找到 <code>public/index.html</code> 通过配置 CDN Config 依次注入 css 和 js。修改 head 的内容如下:</p>
<figure class="highlight html"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">&quot;utf-8&quot;</span> /&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">&quot;X-UA-Compatible&quot;</span> <span class="hljs-attr">content</span>=<span class="hljs-string">&quot;IE=edge,chrome=1&quot;</span> /&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span></span><br><span class="hljs-tag">    <span class="hljs-attr">name</span>=<span class="hljs-string">&quot;viewport&quot;</span></span><br><span class="hljs-tag">    <span class="hljs-attr">content</span>=<span class="hljs-string">&quot;width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no&quot;</span></span><br><span class="hljs-tag">  /&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">&quot;icon&quot;</span> <span class="hljs-attr">href</span>=<span class="hljs-string">&quot;&lt;%= BASE_URL %&gt;favicon.ico&quot;</span> /&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>&lt;%= webpackConfig.name %&gt;<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span><br><br>  <span class="hljs-comment">&lt;!-- 引入样式 --&gt;</span><br>  &lt;% for(var css of htmlWebpackPlugin.options.cdn.css) &#123; %&gt;<br>  <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">&quot;stylesheet&quot;</span> <span class="hljs-attr">href</span>=<span class="hljs-string">&quot;&lt;%=css%&gt;&quot;</span> /&gt;</span><br>  &lt;% &#125; %&gt;<br><br>  <span class="hljs-comment">&lt;!-- 引入JS --&gt;</span><br>  &lt;% for(var js of htmlWebpackPlugin.options.cdn.js) &#123; %&gt;<br>  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">&quot;&lt;%=js%&gt;&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span><br>  &lt;% &#125; %&gt;<br><span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span><br></code></pre></div></td></tr></table></figure>

<h2 id="五、-打包去除-console-log"><a href="#五、-打包去除-console-log" class="headerlink" title="五、 打包去除 console.log"></a>五、 打包去除 <code>console.log</code></h2><h3 id="1-需求-3"><a href="#1-需求-3" class="headerlink" title="1. 需求"></a>1. 需求</h3><p>在项目打包上线后，去除掉代码中所有的 <code>console.log</code></p>
<h3 id="2-代码演示"><a href="#2-代码演示" class="headerlink" title="2. 代码演示"></a>2. 代码演示</h3><p>在 <code>vue.config.js</code> 文件中配置：<br>代码如下（示例）：</p>
<figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs JavaScript"><span class="hljs-title function_">chainWebpack</span>(<span class="hljs-params">config</span>) &#123;<br>  config.<span class="hljs-property">optimization</span>.<span class="hljs-title function_">minimizer</span>(<span class="hljs-string">&#x27;terser&#x27;</span>).<span class="hljs-title function_">tap</span>(<span class="hljs-function">(<span class="hljs-params">args</span>) =&gt;</span> &#123;<br>    args[<span class="hljs-number">0</span>].<span class="hljs-property">terserOptions</span>.<span class="hljs-property">compress</span>.<span class="hljs-property">drop_console</span> = <span class="hljs-literal">true</span><br>    <span class="hljs-keyword">return</span> args<br>  &#125;)<br>&#125;<br></code></pre></div></td></tr></table></figure>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/Vue-js/">Vue.js</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Vue-js/">#Vue.js</a>
                    
                      <a class="hover-with-bg" href="/tags/%E5%89%8D%E7%AB%AF/">#前端</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/03/08/article-8/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">24个 JavaScript 循环遍历方法，你都知道吗？</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/03/08/article-6/">
                        <span class="hidden-mobile">优雅的 JavaScript 个技巧</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://cdn.jsdelivr.net/npm/valine@1/dist/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"A6A3KekcB19LfYQfObiJlDAu-gzGzoHsz","appKey":"h5J0Jt6wCaR3HtH5I0brXmRk","path":"window.location.pathname","placeholder":null,"avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          Fluid.plugins.initFancyBox('#valine .vcontent img:not(.vemoji)');
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->

  <div class="col-lg-7 mx-auto nopadding-x-md">
    <div class="container custom post-custom mx-auto">
      <div style="display: flex;align-items: center;flex-wrap: wrap;flex-direction: row;justify-content: flex-start;"> <img src="https://octodex.github.com/images/jetpacktocat.png" srcset="/img/loading.gif" lazyload class="rounded mx-auto d-block mt-5" style="width:150px; height:150px;"> <img src="https://octodex.github.com/images/jetpacktocat.png" srcset="/img/loading.gif" lazyload class="rounded mx-auto d-block mt-5" style="width:150px; height:150px;"> <img src="https://octodex.github.com/images/jetpacktocat.png" srcset="/img/loading.gif" lazyload class="rounded mx-auto d-block mt-5" style="width:150px; height:150px;"> <img src="https://octodex.github.com/images/jetpacktocat.png" srcset="/img/loading.gif" lazyload class="rounded mx-auto d-block mt-5" style="width:150px; height:150px;"> <img src="https://octodex.github.com/images/jetpacktocat.png" srcset="/img/loading.gif" lazyload class="rounded mx-auto d-block mt-5" style="width:150px; height:150px;"> </div>
    </div>
  </div>


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> <div style="font-size: 0.85rem"> <span id="timeDate">载入天数...</span> <span id="times">载入时分秒...</span> <script src="/js/duration.js"></script> </div> 
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- LeanCloud 统计PV -->
        <span id="leancloud-site-pv-container" style="display: none">
            总访问量 
            <span id="leancloud-site-pv"></span>
             次
          </span>
      
      
        <!-- LeanCloud 统计UV -->
        <span id="leancloud-site-uv-container" style="display: none">
            总访客数 
            <span id="leancloud-site-uv"></span>
             人
          </span>
      

    
  </div>


  
  <!-- 备案信息 -->
  <div class="beian">
    <span>
      <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
        京ICP证123456号
      </a>
    </span>
    
      
        <span>
          <a
            href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=12345678"
            rel="nofollow noopener"
            class="beian-police"
            target="_blank"
          >
            
              <span style="visibility: hidden; width: 0">|</span>
              <img src="/img/police_beian.png" srcset="/img/loading.gif" lazyload alt="police-icon"/>
            
            <span>京公网安备12345678号</span>
          </a>
        </span>
      
    
  </div>


  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  




  <script defer src="/js/leancloud.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>












  
    <!-- Baidu Analytics -->
    <script defer>
      var _hmt = _hmt || [];
      (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?b2ef8b4e438bfbfa9667837d1124fb6c";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
    </script>
  

  

  

  

  

  





<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
